<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :show-close="false"
    :close-on-click-modal="false"
    width="700px"
    center
  >
    <el-form :model="formData">
      <el-form-item label="用户名">
        <el-input v-model="formData.username" placeholder="请输入用户名" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="formData.phone" placeholder="请输入手机号" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="formData.email" placeholder="请输入邮箱" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="item in userStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">返回</el-button>
      <el-button type="primary" @click="submitDialog">提交</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: 'MenuDialog',
}
</script>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { SysUser } from '@/types/index'
import emitter from '@/utils/emitter'
import { addUser, updateUser } from '@/http/api'
import { userStatus } from '@/utils/dicts/user'

const props = defineProps({
  displayFlag: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  userData: {
    type: Object as () => SysUser,
    required: true,
  },
})

const dialogVisible = ref(props.displayFlag)
const dialogTitle = ref(props.title)
const formData = reactive<SysUser>(props.userData)
const closeDialog = () => {
  emitter.emit('update:displayFlag', false)
  emitter.emit('refresh:userTableData')
}
const submitDialog = () => {
  if (!formData.id) {
    addUser(formData)
      .then(() => {
        closeDialog()
      })
      .catch((err) => {
        console.log(err)
      })
  } else {
    updateUser(formData)
      .then(() => {
        closeDialog()
      })
      .catch((err) => {
        console.log(err)
      })
  }
}
</script>
